from sqlalchemy import Column, String, Text, BigInteger, Boolean, DateTime, ForeignKey, Integer
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.orm import relationship
from datetime import datetime
import uuid

from db.base import Base


class PersonalDocument(Base):
    """个人文档模型 - 用于管理用户的个人文档"""
    __tablename__ = "personal_document"

    id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
    title = Column(String(255), nullable=False, comment="文档标题")
    description = Column(Text, comment="文档描述")
    filename = Column(String(255), nullable=False, comment="原始文件名")
    file_path = Column(Text, nullable=False, comment="文件存储路径")
    file_size = Column(BigInteger, nullable=False, comment="文件大小(字节)")
    file_type = Column(String(50), nullable=False, comment="文件类型")
    mime_type = Column(String(100), comment="MIME类型")
    
    # 分类关联
    category_id = Column(UUID(as_uuid=True), ForeignKey("document_category.id"), comment="所属分类ID")
    
    # 状态字段
    is_favorite = Column(Boolean, default=False, comment="是否收藏")
    is_pinned = Column(Boolean, default=False, comment="是否置顶")
    view_count = Column(Integer, default=0, comment="查看次数")
    
    # 时间字段
    created_at = Column(DateTime, default=datetime.utcnow(), comment="创建时间")
    updated_at = Column(DateTime, default=datetime.utcnow(), onupdate=datetime.utcnow(), comment="更新时间")
    last_accessed_at = Column(DateTime, comment="最后访问时间")

    # 关系定义
    category = relationship("DocumentCategory", back_populates="documents")
    tags = relationship("DocumentTag", secondary="document_tag_relation", back_populates="documents")
    compliance_relations = relationship("DocumentComplianceRelation", back_populates="document", cascade="all, delete-orphan")

    def __repr__(self):
        return f"<PersonalDocument(id={self.id}, title='{self.title}', filename='{self.filename}')>"
